<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="120px" size="mini">
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="日期" prop="dailyReportDate">
            <el-date-picker v-model="formItem.dailyReportDate" type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择日报时间" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="运维小组" prop="operationGroupCode">
            <el-select v-model="formItem.operationGroupCode" disabled placeholder="请选择运维小组" style="width:100%">
              <el-option v-for="(item) in groups" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位" prop="unitCode">
            <el-select v-model="formItem.unitCode" placeholder="请选择单位" style="width:100%" filterable clearable :disabled="unableSelectUnit" @change="onChangeUnitCode">
              <el-option v-for="item in availableInstitutions" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="处理人" prop="incidentUserCode">
            <el-select v-model="formItem.incidentUserCode" placeholder="请选择事件处理人" filterable clearable :disabled="unableSelectUnit" style="width:100%" @change="onChangeIncidentUserCode">
              <el-option v-for="(item) in residentsOfCurrInst" :key="item.username" :label="item.name" :value="item.username" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务时间" prop="time">
            <el-time-picker
              v-model="formItem.time"
              format="HH:mm"
              is-range
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="timeChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工作总时长（分）" prop="totalWorkingHours">
            <el-input v-model="formItem.totalWorkingHours" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="工作内容" prop="jobContent">
            <el-input v-model="formItem.jobContent" placeholder="请输入工作内容" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="请求人/处室" prop="eventRequester">
            <el-input v-model="formItem.eventRequester" placeholder="请输入事件请求人/处室" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="处理地点" prop="incidentLocation">
            <el-input v-model="formItem.incidentLocation" placeholder="请输入事件处理地点" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="事件等级" prop="eventLevel">
            <el-select v-model="formItem.eventLevel" clearable placeholder="请选择响应方式" style="width:100%">
              <el-option v-for="(item) in eventgradeList" :key="item.code" :label="item.text" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="响应方式" prop="responseMethod">
            <el-select v-model="formItem.responseMethod" placeholder="请选择响应方式" style="width:100%">
              <el-option v-for="(item) in responseMethodList" :key="item.code" :label="item.text" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务类型" prop="serviceTypeCode">
            <el-select v-model="formItem.serviceTypeCode" clearable placeholder="服务类型" style="width:100%" @change="typeChange">
              <el-option v-for="(item) in worktypes" :key="item.code" :label="item.text" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务属性" prop="serviceAttributesCode">
            <el-select v-model="formItem.serviceAttributesCode" clearable placeholder="服务属性" style="width:100%">
              <el-option v-for="(item) in workpropertys" :key="item.code" :label="item.text" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务单号" prop="trackingNo">
            <el-input v-model="formItem.trackingNo" placeholder="请选择服务单号" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="formItem.remarks" placeholder="请输入" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件">
            <el-upload
              class="upload-demo"
              :headers="headers"
              :action="importUrl"
              :file-list="formItem.attachment"
              :on-success="handleSuccess"
              :on-error="handleError"
              :on-remove="handleRemove"
              :show-file-list="true"
            >
              <el-button size="small" type="primary" icon="el-icon-upload2">上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { create, update, detail, uploadFileUrl } from '@neu/dcom-ui/api/workDaily'
import { list as dList } from '@neu/dcom-ui/api/dictionary'
import { list as groupList } from '@neu/dcom-ui/api/operationGroup'
import { formatDate } from '@neu/biz-core/utils/utils'
import { mapState, mapGetters } from 'vuex'
import { getToken } from '@neu/biz-core/utils/auth'
import { deepClone } from '@neu/biz-core/utils'
// 定义一个表单原始项
const formItem = {
  /** 日报日期 */
  dailyReportDate: formatDate(new Date()),
  /** 单位编码 */
  unitCode: '',
  /** 单位名称 */
  unitName: '',
  /** 运维小组编码 */
  operationGroupCode: '',
  /** 运维小组名称 */
  operationGroupName: '',
  /** 事件请求人/处室 */
  eventRequester: '',
  /** 响应方式 */
  responseMethod: 'resident',
  /** 事件处理地点 */
  incidentLocation: '',
  /** 事件处理人编码 */
  incidentUserCode: '',
  /** 事件处理人名称 */
  incidentUserName: '',
  /** 服务类型编码 */
  serviceTypeCode: '',
  /** 服务类型名称 */
  serviceTypeName: '',
  /** 处理日期 */
  createTime: formatDate(new Date()),
  /** 服务属性编码 */
  serviceAttributesCode: '',
  time: null,
  /** 服务属性名称 */
  serviceAttributesName: '',
  /** 服务开始时间 */
  serviceStartTime: '',
  /** 服务结束时间 */
  serviceEndTime: '',
  /** 事件等级 */
  eventLevel: '',
  /** 工作总时长 */
  totalWorkingHours: 0,
  /** 服务单号 */
  trackingNo: '',
  /** 工作内容 */
  jobContent: '',
  /** 备注 */
  remarks: '',
  /** 附件 */
  attachment: []
}

const formRules = {
  dailyReportDate: [{ required: true, message: '日报日期为空', trigger: 'blur' }],
  unitCode: [{ required: true, message: '单位不能为空', trigger: 'blur' }],
  time: [{ required: true, message: '服务时间不能为空', trigger: 'blur' }],
  totalWorkingHours: [{ required: true, message: '工作总时长不能为空', trigger: 'blur' }],
  jobContent: [{ required: true, message: '工作内容不能为空', trigger: 'blur' }],
  operationGroupCode: [{ required: true, message: '运维小组不能为空', trigger: 'blur' }],
  incidentUserCode: [{ required: true, message: ' 事件处理人不能为空', trigger: 'blur' }]
}

export default {
  name: 'WorkDailyEditForm',
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      /** 行数 */
      rows: 2,
      // 所有单位
      availableInstitutions: [],
      // 表单验证规则
      rules: { ...formRules },
      // 所有服务类型
      worktypes: [],
      // 二级服务属性
      workpropertys: [],
      // 运维小组
      groups: [],
      // 响应方式
      responseMethodList: [],
      // 事件等级集合
      eventgradeList: [],
      // 当前选中单位下的驻场人员
      residentsOfCurrInst: [],
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      },
      importUrl: uploadFileUrl
    }
  },
  computed: {
    ...mapState({
      name: state => state.user.name
    }),
    ...mapGetters([
      'roles'
    ]),
    projectUserInfo() {
      return this.$store.getters['dcom/projectUserInfo']
    },
    // 是否可选择厅局
    unableSelectUnit() {
      return this.roles.some(r => r === 'worker')
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function() {
      this.fetch()
    }
  },
  created() {
    this.availableInstitutions = this.$store.getters['dcom/projectUserInfo'].institutions
    this.formItem.operationGroupCode = this.$store.getters['dcom/projectUserInfo'].groupCode
    this.fetch()
    // 查询字典表服务类型
    dList({ s_type: 'worktype' }).then(res => {
      this.worktypes = res.data
    })
    // 获取小组
    groupList().then(res => {
      this.groups = res.data
    })

    // 响应方式
    dList({ s_type: 'responseMethod' }).then(res => {
      this.responseMethodList = res.data
    })

    // 事件等级
    dList({ s_type: 'eventgrade' }).then(res => {
      this.eventgradeList = res.data
    })

    // 默认当天日期
    this.formItem.createTime = formatDate(new Date())
    // 默认登录人
    // this.formItem.incidentUserName = this.$store.state.user.name
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          const data = response.data
          if (data.attachment) {
            const fileJoins = data.attachment.split('||')
            data.attachment = fileJoins.map(it => {
              const fsInfo = it.split('@@')
              return {
                fsId: fsInfo[0],
                name: fsInfo[1]
              }
            })
          } else {
            data.attachment = []
          }
          if (data.serviceTypeCode) {
            this.getFormList(data.serviceTypeCode)
          }
          this.formItem = {
            ...data,
            time: data.serviceStartTime ? [data.serviceStartTime, data.serviceEndTime] : []
          }
          this.initDefaultIncidentUser()
        })
      } else {
        this.formItem = {
          ...formItem
        }
        this.formItem.unitCode = this.$store.getters['dcom/projectUserInfo'].defaultInstituteCode
        this.formItem.operationGroupCode = this.$store.getters['dcom/projectUserInfo'].groupCode
        // const inst = this.availableInstitutions.find(it => it.code === this.formItem.unitCode)
        // if (inst) {
        //   this.residentsOfCurrInst = [...inst.residents, ...inst.users]
        //   let currentResidentUser = inst.residents.find(it => it.name === this.name)
        //   if (!currentResidentUser) {
        //     currentResidentUser = inst.residents.length > 0 ? inst.residents[0] : {}
        //   }
        //   this.formItem.incidentUserCode = currentResidentUser.username
        //   this.formItem.incidentUserName = currentResidentUser.name
        // }
        this.initDefaultIncidentUser()
      }
    },
    initDefaultIncidentUser() {
      const inst = this.availableInstitutions.find(it => it.code === this.formItem.unitCode)
      if (inst) {
        this.residentsOfCurrInst = [...inst.residents, ...inst.users]
        let currentResidentUser = inst.residents.find(it => it.name === this.name)
        if (!currentResidentUser) {
          currentResidentUser = inst.residents.length > 0 ? inst.residents[0] : {}
        }
        this.formItem.incidentUserCode = currentResidentUser.username
        this.formItem.incidentUserName = currentResidentUser.name
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            // 公司名称
            const institutions = this.availableInstitutions.find(e => this.formItem.unitCode === e.code)
            this.formItem.unitName = institutions ? institutions.name : ''
            // 运维开始结束时间
            if (this.formItem.time) {
              this.formItem.serviceStartTime = this.formItem.time[0]
              this.formItem.serviceEndTime = this.formItem.time[1]
            }

            // 小组名称
            const group = this.groups.find(e => e.code === this.formItem.operationGroupCode)
            this.formItem.operationGroupName = group ? group.name : ''

            // 服务属性
            const serviceAttributes = this.workpropertys.find(e => e.code === this.formItem.serviceAttributesCode)
            this.formItem.serviceAttributesName = serviceAttributes ? serviceAttributes.text : ''
            const deepCloneForm = deepClone(this.formItem)
            // 将附件转为字符串存储
            if (deepCloneForm.attachment.length > 0) {
              deepCloneForm.attachment = deepCloneForm.attachment.map(it => it.fsId + '@@' + it.name).join('||')
            } else {
              deepCloneForm.attachment = ''
            }
            if (updated) {
              resolve(update(this.id, deepCloneForm))
            } else {
              resolve(create(deepCloneForm))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
      this.formItem.time = null
    },
    // 根据类型获取服务属性
    typeChange(val) {
      this.workpropertys = []
      this.formItem.serviceAttributesCode = ''
      if (val) {
        this.getFormList(val)
      }
      // 获取服务类型名
      const name = this.worktypes.find((item) => {
        return item.code === val
      })
      this.formItem.serviceTypeName = name ? name.text : ''
    },
    // 获取服务属性二级菜单
    getFormList(type) {
      dList({ s_type: type }).then(res => {
        this.workpropertys = res.data
      })
    },
    timeChange(val) {
      if (val) {
        const v1 = new Date(val[0])
        const v2 = new Date(val[1])
        this.formItem.totalWorkingHours = (v2.getHours() * 60 + v2.getMinutes()) - (v1.getHours() * 60 + v1.getMinutes())
      } else {
        this.formItem.totalWorkingHours = 0
      }
    },
    onChangeUnitCode(value) {
      this.formItem.incidentUserCode = ''
      this.formItem.incidentUserName = ''
      const inst = this.availableInstitutions.find(it => it.code === value)
      if (inst) {
        this.residentsOfCurrInst = this.residentsOfCurrInst = [...inst.residents, ...inst.users]
        // 先判断当前登录用户是否在选中单位下的驻场人员
        let currentResidentUser = inst.residents.find(it => it.name === this.name)
        if (!currentResidentUser) {
          currentResidentUser = inst.residents.length > 0 ? inst.residents[0] : {}
        }
        this.formItem.incidentUserCode = currentResidentUser.username
        this.formItem.incidentUserName = currentResidentUser.name
      }
    },
    onChangeIncidentUserCode(incidentUserCode) {
      const user = this.residentsOfCurrInst.find(item => item.username === incidentUserCode)
      this.formItem.incidentUserName = user.name
    },
    /** 文件上传成功 */
    handleSuccess(response, file, fileList) {
      if (response.status === 'failure') {
        this.$message({
          showClose: true,
          message: response.data,
          type: 'error'
        })
      } else {
        const obj = {
          fsId: response.data.fsId,
          name: response.data.name
        }
        const fsIdArr = this.formItem.attachment.map(t => t.fsId)
        if (!fsIdArr.includes(obj.fsId)) {
          this.formItem.attachment.push(obj)
        } else {
          fileList.pop()
        }
      }
    },
    /** 文件上传失败 */
    handleError(err, file, fileList) {
      console.log(err)
    },
    /** 文件移除 */
    handleRemove(file, fileList) {
      this.formItem.attachment.splice(this.formItem.attachment.indexOf(file), 1)
    }
  }
}
</script>
